﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CML.Intercamber.Business;
using CML.Intercamber.Business.Dao;
using CML.Intercamber.Business.Model;
using CML.Intercamber.Web.Helpers;
using CML.Intercamber.Web.Helpers.ModelHelper;
using CML.Intercamber.Web.Models;
using MvcJqGrid;

namespace CML.Intercamber.Web.Controllers
{
    [Authorize]
    //[InitializeSimpleMembership]
    public class TalkController : BaseController
    {

        public ActionResult Discussion(long id)
        {
            ViewBag.MyThreads = ThreadHelper.ThreadDetails;
            ViewBag.Me = ConnectedUserHelper.ConnectedUser;

            var discussionThreadInfo = ContactsHelper.ContactDetails(ConnectedUserHelper.ConnectedUserId).FirstOrDefault(x => x.IdUser == id);
            if (discussionThreadInfo == null)
                return RedirectToAction("Index", "Home");

            ThreadsDao dao = new ThreadsDao();
            Threads t = dao.GetThreads(ConnectedUserHelper.ConnectedUserId, id);
            if (t == null)
            {
                t = dao.CreateThreads(ConnectedUserHelper.ConnectedUserId, id);
                var allThreads = ThreadHelper.ThreadDetails;
                if (allThreads.All(x => x.IdThread != t.IdThread))
                    ThreadHelper.ReloadThreadDetails();
            }
            ViewBag.IdThread = t.IdThread;

            // mark discussion as read
            List<UsersDetail> cd = ViewBag.MyContacts;
            UsersDetail contact = cd.FirstOrDefault(x => x.IdUser == id);
            if (contact != null)
            {
                ViewBag.Dest = contact;
                if (contact.NumUnreadMessages > 0)
                {
                    ThreadUsersDao threadUsersDao = new ThreadUsersDao();
                    threadUsersDao.UpdateThreadRead(ConnectedUserHelper.ConnectedUserId, t.IdThread, DateTime.Now);
                    contact.NumUnreadMessages = 0;
                    UnreadMessageHelper.RefreshCache(ConnectedUserHelper.ConnectedUserId);
                }
            }

            //var dao = new ThreadUsersDao();
            //dao.UpdateThreadRead(ConnectedUserHelper.ConnectedUserId, threadId, DateTime.Now);
            //UnreadMessageHelper.RefreshCache(ConnectedUserHelper.ConnectedUserId);

            return View();
        }

        public const int NbMessagesPerHistoryRequest = 20;

        /// <summary>
        /// return latest NbMessagesPerHistoryRequest messages, before message id messageIdMax
        /// </summary>
        /// <param name="idThread"></param>
        /// <param name="messageIdMax"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ChatHistory(long? idThread, long? messageIdMax)
        {
            ThreadMessagesDao dao = new ThreadMessagesDao();
            if (idThread == null || ThreadHelper.ThreadDetails.All(x => x.IdThread != idThread.Value))
                if(!ConnectedUserHelper.IsAdmin)
                    return null;

            var historique = dao.ListThreadMessagesByParameters(idThread.Value, messageIdMax, NbMessagesPerHistoryRequest);
            List<ChatMessage> messages = historique.Select(x => new ChatMessage
            {
                Id = x.IdMessage,
                IdUser = x.IdUser,
                Message = x.Message,
                Correction = x.MessageCorrection,
                Date = x.DateMessage
            }).ToList();
            ThreadActionsDao daoActions = new ThreadActionsDao();
            if (messageIdMax == null)
                messages.AddRange(daoActions.ListThreadMessagesByParameters(idThread.Value).Select(x => new ChatMessage
                {
                    Id = null,
                    IdUser = x.IdUser,
                    Message = x.Params,
                    Action = x.CodeAction,
                    Date = x.DateAction
                }).ToList());
            messages = messages.OrderByDescending(x => x.Date).ToList();

            return Json(new { d = messages, ps = NbMessagesPerHistoryRequest }, JsonRequestBehavior.AllowGet);
        }

        #region translation history 

        public ActionResult Translations()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AddTranslation(string idLang, string search)
        {
            var connectedUser = ConnectedUserHelper.ConnectedUser;
            if (connectedUser == null || string.IsNullOrEmpty(search))
                return null;

            TranslationHistoryDao.InsertTranslationHistory(new TranslationHistory()
            {
                IdUser = connectedUser.IdUser,
                DateSearch = DateTime.Now,
                IdLanguage = idLang,
                Starred = false,
                Word = search.Length > 256 ? search.Substring(0, 256) : search
            });

            return Json(true);
        }

        [HttpPost]
        public JsonResult DeleteTranslation(long id)
        {
            var connectedUser = ConnectedUserHelper.ConnectedUser;
            if (connectedUser == null)
                return null;

            TranslationHistoryDao.DeleteTranslationHistory(id);
                
            return Json(true);
        }


        [HttpPost]
        public JsonResult ToggleTranslationStar(long id, bool starred)
        {
            var connectedUser = ConnectedUserHelper.ConnectedUser;
            if (connectedUser == null)
                return null;

            TranslationHistoryDao.ToggleTranslationHistoryStar(id, starred);
             
            return Json(true);
        }

        public JsonResult TranslationsData(GridSettings gridSettings)
        {
            var connectedUser = ConnectedUserHelper.ConnectedUser;
            if (connectedUser == null) return null;

            List<TranslationHistoryDetail> data = TranslationHistoryDao.ListTranslationsHistory(connectedUser.IdUser);
            data.ForEach(x => {
                x.LblLanguage = ResourcesHelper.GetString("Languages_" + x.IdLanguage);
            });
            var res = new GridData<TranslationHistoryDetail>
            {
                page = 1, // number of requested page
                records = data.Count, // total records from query 
                total = 1, // total pages of query 
                rows = data
            };
            return Json(res, JsonRequestBehavior.AllowGet);
        }
        #endregion 

        #region page my discussions

        public ActionResult MyDiscussions()
        {
            return View();
        }

        public JsonResult MyDiscussionsData(GridSettings gridSettings)
        {
            ThreadsDao dao = new ThreadsDao();
            List<ThreadReportDetail> data = dao.ThreadReport(ConnectedUserHelper.ConnectedUserId);
            data.ForEach(UsersDetailHelper.FilDataInBean);
            var res = new GridData<ThreadReportDetail>
            {
                page = 1, // number of requested page
                records = data.Count, // total records from query 
                total = 1, // total pages of query 
                rows = data
            };
            return Json(res, JsonRequestBehavior.AllowGet);
        }


        #endregion

    }
}
